package com.ruoyi.module.controller;

import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.module.domain.UserSettings;
import com.ruoyi.module.service.IUserSettingsService;

/**
 * 用户设置Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/user")
public class UserSettingsController extends BaseController
{
    @Autowired
    private IUserSettingsService userSettingsService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 获取用户设置
     */
    @GetMapping("/settings")
    public AjaxResult getSettings()
    {
        try {
            Long userId = SecurityUtils.getUserId();
            UserSettings settings = userSettingsService.selectUserSettingsByUserId(userId);
            
            if (settings == null) {
                // 如果用户没有设置记录，创建默认设置
                settings = new UserSettings();
                settings.setUserId(userId);
                settings.setCurrentDictId("cet4");
                settings.setCurrentChapter(0);
                settings.setCurrentEvalId("cet4");
                settings.setCurrentEvalChapter(0);
                settings.setSettingsJson("{}");
                userSettingsService.insertUserSettings(settings);
            }
            
            // 解析settingsJson为对象返回
            Map<String, Object> result = new java.util.HashMap<>();
            result.put("currentDictId", settings.getCurrentDictId());
            result.put("currentChapter", settings.getCurrentChapter());
            result.put("currentEvalId", settings.getCurrentEvalId());
            result.put("currentEvalChapter", settings.getCurrentEvalChapter());
            
            if (settings.getSettingsJson() != null && !settings.getSettingsJson().isEmpty()) {
                try {
                    Map<String, Object> settingsMap = objectMapper.readValue(
                        settings.getSettingsJson(),
                        new com.fasterxml.jackson.core.type.TypeReference<Map<String, Object>>(){}
                    );
                    result.put("settings", settingsMap);
                } catch (Exception e) {
                    result.put("settings", new java.util.HashMap<>());
                }
            } else {
                result.put("settings", new java.util.HashMap<>());
            }
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("获取用户设置失败", e);
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 更新用户设置
     */
    @Log(title = "更新用户设置", businessType = BusinessType.UPDATE)
    @PutMapping("/settings")
    public AjaxResult updateSettings(@RequestBody Map<String, Object> params)
    {
        try {
            Long userId = SecurityUtils.getUserId();
            UserSettings settings = userSettingsService.selectUserSettingsByUserId(userId);
            
            if (settings == null) {
                // 创建新设置
                settings = new UserSettings();
                settings.setUserId(userId);
                settings.setCurrentDictId("cet4");
                settings.setCurrentChapter(0);
                settings.setCurrentEvalId("cet4");
                settings.setCurrentEvalChapter(0);
                settings.setSettingsJson("{}");
            }
            
            // 更新字段
            if (params.containsKey("currentDictId")) {
                settings.setCurrentDictId((String) params.get("currentDictId"));
            }
            if (params.containsKey("currentChapter")) {
                settings.setCurrentChapter((Integer) params.get("currentChapter"));
            }
            if (params.containsKey("currentEvalId")) {
                settings.setCurrentEvalId((String) params.get("currentEvalId"));
            }
            if (params.containsKey("currentEvalChapter")) {
                settings.setCurrentEvalChapter((Integer) params.get("currentEvalChapter"));
            }
            if (params.containsKey("settings")) {
                settings.setSettingsJson(objectMapper.writeValueAsString(params.get("settings")));
            }
            
            // 保存或更新
            if (settings.getId() == null) {
                userSettingsService.insertUserSettings(settings);
            } else {
                userSettingsService.updateUserSettings(settings);
            }
            
            return AjaxResult.success("设置已保存");
        } catch (Exception e) {
            logger.error("更新用户设置失败", e);
            return AjaxResult.error("保存失败: " + e.getMessage());
        }
    }

    /**
     * 批量更新配置项
     */
    @Log(title = "批量更新配置项", businessType = BusinessType.UPDATE)
    @PutMapping("/settings/batch")
    public AjaxResult batchUpdateSettings(@RequestBody Map<String, Object> params)
    {
        try {
            Long userId = SecurityUtils.getUserId();
            UserSettings settings = userSettingsService.selectUserSettingsByUserId(userId);
            
            if (settings == null) {
                return AjaxResult.error("用户设置不存在");
            }
            
            // 获取updates对象
            Map<String, Object> updates = (Map<String, Object>) params.get("updates");
            if (updates == null || updates.isEmpty()) {
                return AjaxResult.error("更新内容为空");
            }
            
            // 解析现有设置
            Map<String, Object> currentSettings = new java.util.HashMap<>();
            if (settings.getSettingsJson() != null && !settings.getSettingsJson().isEmpty()) {
                try {
                    currentSettings = objectMapper.readValue(
                        settings.getSettingsJson(),
                        new com.fasterxml.jackson.core.type.TypeReference<Map<String, Object>>(){}
                    );
                } catch (Exception e) {
                    logger.warn("解析现有设置失败，使用空设置", e);
                }
            }
            
            // 合并更新
            currentSettings.putAll(updates);
            
            // 保存
            settings.setSettingsJson(objectMapper.writeValueAsString(currentSettings));
            userSettingsService.updateUserSettings(settings);
            
            return AjaxResult.success("设置已更新");
        } catch (Exception e) {
            logger.error("批量更新配置项失败", e);
            return AjaxResult.error("更新失败: " + e.getMessage());
        }
    }
}

